/*
 * Copyright (c) 2006 by Naohide Sano, All rights reserved.
 *
 * Programmed by Naohide Sano
 */

package vavix.awt.image.color;

import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;


/**
 * CreateMaskOp.
 *
 * @author <a href="mailto:vavivavi@yahoo.co.jp">Naohide Sano</a> (nsano)
 * @version 0.00 060616 nsano initial version <br>
 */
public class CreateMaskOp implements BufferedImageOp {

    /** マスク */
    private int argb;

    /**
     * TODO hints, mask color
     */
    public CreateMaskOp(int argb) {
        this.argb = argb;
    }

    /** */
    public CreateMaskOp(int r, int g, int b) {
        this.argb = ((r & 0xff) << 24) | ((g & 0xff) << 16) | (b & 0xff);
    }

    /**
     * マスクは今のところ {@link #argb} が #ffffff で、そうでないところが #000000 固定
     * @param src should be indexed color model
     * @param dst when null, created by {@link #createCompatibleDestImage(BufferedImage, ColorModel)} 
     */
    public BufferedImage filter(BufferedImage src, BufferedImage dst) {
        if (dst == null) {
            dst = createCompatibleDestImage(src, null);
        }
        
        int targetRgb = src.isAlphaPremultiplied() ? argb : argb | 0xff000000;

        for (int y = 0; y < src.getHeight(); y++) {
            for (int x = 0; x < src.getWidth(); x++) {
                if (src.getRGB(x, y) == targetRgb) {
                    dst.setRGB(x, y, 0xffffffff);
                } else {
                    dst.setRGB(x, y, 0xff000000);
                }
            }
        }

        return dst;
    }

    /**
     * @return always return B&W color model 
     */
    public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
        Rectangle destBounds = (Rectangle) getBounds2D(src);
        return new BufferedImage(destBounds.width, destBounds.height, BufferedImage.TYPE_BYTE_BINARY);
    }

    /** */
    public Rectangle2D getBounds2D(BufferedImage src) {
        return new Rectangle(0, 0, src.getWidth(), src.getHeight());
    }

    /** */
    public Point2D getPoint2D(Point2D srcPt, Point2D dstPt) {
        if (dstPt == null) {
            dstPt = new Point2D.Double();
        }
        dstPt.setLocation(srcPt.getX(), srcPt.getY());
        return dstPt;
    }

    /** TODO impl */
    public RenderingHints getRenderingHints() {
        return null;
    }
}

/* */
